package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户参数解析器
 * 将当前登录用户对象，注入到请求印射方法声明的UserInfo参数变量中
 * @PostMapping("/info")
 * public Object info(UserInfo userInfo){
 *     // 此时userInfo是当前登录用户信息
 *     return JsonResult.success(userInfo)
 * }
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    //设置当前解析器支持的解析参数类型
    //此次设置支持解析参数类型：UserInfo
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType()== UserInfo.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        //解析参数并注入参数值
        //简单理解：获取当前登录对象，并注入到映射方法的UserInfo参数变量中
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");
        UserInfo userInfo = userInfoRedisService.findUserInfoByToken(token);
        //springmvc会自动将返回值注入到userInfo变量中
        return userInfo;
    }
}
